import { ref, onMounted, onBeforeUnmount, nextTick } from 'vue'

// ECharts动态加载Hook
export const useECharts = (containerRef: any) => {
  const chart = ref<any>(null)
  const loading = ref(false)

  // 动态加载ECharts
  const loadECharts = async () => {
    loading.value = true

    try {
      // 动态导入ECharts核心模块和主题
      const [echartsCore] = await Promise.all([
        import('echarts/core'),
      ])

      const echarts = echartsCore.default

      // 按需导入组件
      const [
        { default: BarChart },
        { default: LineChart },
        { default: PieChart },
        { default: TitleComponent },
        { default: TooltipComponent },
        { default: LegendComponent },
        { default: GridComponent }
      ] = await Promise.all([
        import('echarts/charts/BarChart'),
        import('echarts/charts/LineChart'),
        import('echarts/charts/PieChart'),
        import('echarts/components/TitleComponent'),
        import('echarts/components/TooltipComponent'),
        import('echarts/components/LegendComponent'),
        import('echarts/components/GridComponent')
      ])

      // 注册组件
      echarts.use([
        BarChart,
        LineChart,
        PieChart,
        TitleComponent,
        TooltipComponent,
        LegendComponent,
        GridComponent
      ])

      return echarts
    } catch (error) {
      console.error('ECharts加载失败:', error)
      throw error
    } finally {
      loading.value = false
    }
  }

  // 初始化图表
  const initChart = async (options: any) => {
    if (!containerRef.value) return

    try {
      const echarts = await loadECharts()

      // 确保DOM已渲染
      await nextTick()

      chart.value = echarts.init(containerRef.value)
      chart.value.setOption(options)

      return chart.value
    } catch (error) {
      console.error('图表初始化失败:', error)
      throw error
    }
  }

  // 更新图表配置
  const updateChart = (options: any) => {
    if (!chart.value) return

    try {
      chart.value.setOption(options, true)
    } catch (error) {
      console.error('图表更新失败:', error)
    }
  }

  // 调整图表大小
  const resizeChart = () => {
    if (!chart.value) return

    try {
      chart.value.resize()
    } catch (error) {
      console.error('图表调整大小失败:', error)
    }
  }

  // 销毁图表
  const destroyChart = () => {
    if (!chart.value) return

    try {
      chart.value.dispose()
      chart.value = null
    } catch (error) {
      console.error('图表销毁失败:', error)
    }
  }

  // 获取图表实例
  const getChartInstance = () => chart.value

  // 组件挂载时添加resize监听
  onMounted(() => {
    window.addEventListener('resize', resizeChart)
  })

  // 组件卸载时清理资源
  onBeforeUnmount(() => {
    window.removeEventListener('resize', resizeChart)
    destroyChart()
  })

  return {
    chart,
    loading,
    initChart,
    updateChart,
    resizeChart,
    destroyChart,
    getChartInstance
  }
}

// 预设图表配置
export const chartPresets = {
  // 置信度环形图配置
  confidenceRing: (data: any[]) => ({
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c}% ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        name: '置信度',
        type: 'pie',
        radius: ['40%', '70%'],
        center: ['60%', '50%'],
        avoidLabelOverlap: false,
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 20,
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: data
      }
    ]
  }),

  // 历史评分趋势图配置
  scoringTrend: (data: any[]) => ({
    title: {
      text: '评分历史趋势',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['UCEIS评分'],
      top: 30
    },
    xAxis: {
      type: 'category',
      data: data.map(item => item.date),
      axisLabel: {
        rotate: 45
      }
    },
    yAxis: {
      type: 'value',
      name: '评分',
      min: 0,
      max: 8
    },
    series: [
      {
        name: 'UCEIS评分',
        data: data.map(item => item.score),
        type: 'line',
        smooth: true,
        areaStyle: {
          opacity: 0.3
        },
        lineStyle: {
          width: 3
        }
      }
    ]
  }),

  // 评分分布柱状图配置
  scoringDistribution: (data: any[]) => ({
    title: {
      text: '评分分布',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    xAxis: {
      type: 'category',
      data: ['0-1分', '2-3分', '4-5分', '6-7分', '8分以上']
    },
    yAxis: {
      type: 'value',
      name: '病例数'
    },
    series: [
      {
        data: data,
        type: 'bar',
        showBackground: true,
        backgroundStyle: {
          color: 'rgba(180, 180, 180, 0.2)'
        }
      }
    ]
  })
}